package net.altran.tests.embedded.cdi_ejb_jpa;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.sql.DataSourceDefinition;

@WebServlet(name = "BasicCDITestServlet",
urlPatterns = "/BasicCDITestServlet")

@DataSourceDefinition(
            name="java:app/jdbc/DB1",
            className="org.apache.derby.jdbc.EmbeddedDataSource",
            portNumber=1527,
            serverName="localhost",
            databaseName="sun-appserv-samples",
            user="APP",
            password="APP",
            properties={"connectionAttributes=;create=true"}
)
public class BasicCDITestServlet extends HttpServlet {

    @javax.inject.Inject
    TestBean testBean;

    @javax.inject.Inject
    TestRequestScopedBean trsb;

    @Override
    protected void doGet(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) throws ServletException, IOException {
        PrintWriter out = httpServletResponse.getWriter();
        out.println("Hi from BasicCDITestServlet");
        if (testBean == null) {
            out.println("TestBean not injected.");
        } else if (trsb == null) {
            out.println("TestRequestScopeBean not injected.");
        } else {
            out.println("TestBean injected. [" + testBean + "]");
            out.println("TestRequestScopeBean injected. [ " + trsb + "]");
            out.println("All CDI beans have been injected.");
        }
        invokeTestBean(out);
        out.flush();
        out.close();
    }

    private void invokeTestBean(PrintWriter out) {
        testBean.addPerson("Ada");
        testBean.addPerson("Bob");
        testBean.addPerson("Cub");
        out.println("Added persons.");

        Person p1 = testBean.getPerson(1L);
        Person p2 = testBean.getPerson(2L);
        Person p3 = testBean.getPerson(3L);
        out.println("Retrieved persons: " + p1 + ", " + p2 + ", " + p3);
    }
}
